/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.service.pf.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.bean.pf.BaseSalaryDetailExcelBean;
import com.plian.system.bean.pf.SalaryDetailExcelBean;
import com.plian.system.constant.baseinfo.ValueSetConstant;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.entity.hr.staff.StaffFiles;
import com.plian.system.entity.pf.BaseSalaryDetail;
import com.plian.system.entity.pf.SalaryDetail;
import com.plian.system.excel.ImportExcelUtil;
import com.plian.system.excel.ImportResult;
import com.plian.system.mapper.pf.BaseSalaryDetailMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.bt.baseinfo.BaseInfoService;
import com.plian.system.service.hr.dept.IDeptService;
import com.plian.system.service.hr.staff.IStaffFilesService;
import com.plian.system.service.pf.IBaseSalaryDetailService;
import com.plian.system.service.pf.ISalaryDetailService;
import com.plian.system.service.sys.code.IFormCodeService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.service.wfTwo.WorkflowTwoService;
import com.plian.system.vo.pf.BaseSalaryDetailVO;
import com.plian.system.vo.pf.SalaryDetailVO;
import com.plian.system.wrapper.pf.BaseSalaryDetailWrapper;
import com.plian.system.wrapper.pf.SalaryDetailWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import static com.plian.system.constant.sys.BaseConstant.BASE64_KEY;
import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * 服务实现类
 *
 * @author
 * @since 2019-09-27
 */
@Slf4j
@Service
@AllArgsConstructor
public class BaseSalaryDetailServiceImpl extends BaseServiceImpl<BaseSalaryDetailMapper, BaseSalaryDetail> implements IBaseSalaryDetailService, BaseFlowService {

	private FormWorkflowService formWorkflowService;

	private IFormCodeService formCodeService;

	private ISalaryDetailService salaryDetailService;

	private BaseInfoService baseInfoService;

	private IDeptService deptService;

	private static Map<Long, String> deptMap = new HashMap<>();

	private static Map<String, String> rankMap = new HashMap<>();

	private OrgzationDao orgzationDao;

	private IStaffFilesService staffFilesService;

	private BaseSalaryDetailWrapper baseSalaryDetailWrapper;

	private SalaryDetailWrapper salaryDetailWrapper;

	private WorkflowTwoService workflowTwoService;


	@Override
	public boolean saveOrUpdate(BaseSalaryDetail baseSalaryDetail) {

		if (!Optional.ofNullable(baseSalaryDetail.getStatus()).isPresent()) {
			baseSalaryDetail.setStatus(FormStatusConstant.UNREVIEWED);
		}
		if (!Optional.ofNullable(baseSalaryDetail.getId()).isPresent()) {
			baseSalaryDetail.setCode(formCodeService.getCode(FormTypeConstant.PF_BASE_SALARY_DETAIL));
			baseSalaryDetail.setFormType(String.valueOf(FormTypeConstant.PF_BASE_SALARY_DETAIL));
		}

		return super.saveOrUpdate(baseSalaryDetail);
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean deleteLogic(List<Long> ids) {
		for (Long id : ids) {
			BaseSalaryDetail baseSalaryDetail = getById(id);
			if (baseSalaryDetail == null) {
				return false;
			} else if (baseSalaryDetail.getStatus() != null &&
					(baseSalaryDetail.getStatus() != FormStatusConstant.STASH && baseSalaryDetail.getStatus() != FormStatusConstant.UNREVIEWED)) {
				return false;
			}
			formWorkflowService.deleteProcessInstance(String.valueOf(id));
		}

		boolean result = super.deleteLogic(ids);
		if (result){
			salaryDetailService.deleteByParentId(ids);
		}
		return result;
	}

	@Override
	public HashMap<String,Object> commit(String id) {
		handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);

		//将需要提交的流程变量返回，用于工作流侧
		return new HashMap<String,Object>();
	}

	@Override
	public Boolean finish(String id) {
		return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
	}

	@Override
	public Boolean reject(String id, int formState, String comment) {
		return handleStatus(Long.valueOf(id), formState);
	}


	@Override
	public String checkYear(BaseSalaryDetail baseSalaryDetail) {
		LambdaQueryWrapper<BaseSalaryDetail> queryWrapper = new LambdaQueryWrapper<>();
		if (!Optional.ofNullable(baseSalaryDetail.getFillingYear()).isPresent()) {
			return "填报年度为空";
		}
		if (!Optional.ofNullable(baseSalaryDetail.getFillingUnitId()).isPresent()){
			return "填报单位为空";
		}
		queryWrapper.eq(BaseSalaryDetail::getFillingUnitId, baseSalaryDetail.getFillingUnitId());
		queryWrapper.eq(BaseSalaryDetail::getFillingYear, baseSalaryDetail.getFillingYear());
		BaseSalaryDetail one = getOne(queryWrapper);
		if (!Optional.ofNullable(one).isPresent()){
			return null;
		}
		if (one.getId().equals(baseSalaryDetail.getId())){
			return null;
		}
		return "该年度已填报";
	}


	/**
	 * 统一处理状态机事件方法
	 *
	 * @param id          主键
	 * @param updateStatus  更新状态
	 * @return boolean
	 */
	private Boolean handleStatus(Long id, int updateStatus) {
		try {
			BaseSalaryDetail baseSalaryDetail = getById(id);
			/**
			 * 设置审批人和审批时间
			 */
			if (updateStatus == FormStatusConstant.FINISH){
				baseSalaryDetail.setApprovedUser(TokenUtil.getTokenUserId());
				Date now = DateUtil.now();
				baseSalaryDetail.setApprovedTime(now);
			}
			baseSalaryDetail.setStatus(updateStatus);
			updateById(baseSalaryDetail);
			return true;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			return false;
		}
	}


	@Override
	public List<PageData> findByIds(List<String> formIds) {
		LambdaQueryWrapper<BaseSalaryDetail> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(BaseSalaryDetail::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
		List<BaseSalaryDetail> baseSalaryDetails = list(queryWrapper);
		List<BaseSalaryDetailVO> baseSalaryDetailVOS= baseSalaryDetailWrapper.entityToVO(baseSalaryDetails);
		List<PageData> pageDataList = new ArrayList<>();
		try{
			if (CollectionUtil.isNotEmpty(baseSalaryDetailVOS)){
				for (BaseSalaryDetailVO vo : baseSalaryDetailVOS){
					PageData pd = new PageData();
					pd.put("id", vo.getId());
					pd.put("UNITNAME", vo.getFillingUnitName());
					pd.put("APPLICANTNAME", vo.getCreateUserName());
					pd.put("applicantId", vo.getCreateUser());
					pd.put("applyOrganizationId", vo.getFillingUnitId());
					pd.put("formType", FormTypeConstant.PF_BASE_SALARY_DETAIL);
					pd.put("orgName", vo.getFillingUnitName());
					pageDataList.add(pd);
				}
			}

			return pageDataList;
		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
		return pageDataList;
	}

	@Override
	public List<Integer> getFormType() {
		return Arrays.asList(FormTypeConstant.PF_BASE_SALARY_DETAIL);
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public boolean submit(BaseSalaryDetail baseSalaryDetail) {
		boolean result = saveOrUpdate(baseSalaryDetail);
		if (result){
			List<SalaryDetail> salaryDetails = baseSalaryDetail.getSalaryDetails();
			if (CollectionUtil.isNotEmpty(salaryDetails)){
				for (SalaryDetail salaryDetail : salaryDetails){
					if (salaryDetail.getId() != null &&
							Optional.ofNullable(salaryDetail.getIsDeleted()).isPresent() && salaryDetail.getIsDeleted().intValue() == 1) {
						salaryDetailService.removeById(salaryDetail.getId());
					}else {
						salaryDetail.setBaseSalaryDetailId(baseSalaryDetail.getId());
						salaryDetailService.saveOrUpdate(salaryDetail);
					}
				}
			}
			if(baseSalaryDetail.getStatus() == 3){
				// 反审核
				goBackToStash(String.valueOf(baseSalaryDetail.getId()));
				workflowTwoService.goBackToStash(String.valueOf(baseSalaryDetail.getId()), FormTypeConstant.HR_STAFFFILES_FORM);
			}
		}
		return result;
	}

	@Override
	public R<BaseSalaryDetailVO> getDetailObj(BaseSalaryDetailVO salaryDetailVO) {
		if(!Optional.ofNullable(salaryDetailVO).isPresent()){
			return new R(CommonCode.FAIL);
		}
		salaryDetailVO.setSalaryDetailVOS(salaryDetailWrapper.entityToVO(
				salaryDetailService.list(new LambdaQueryWrapper<SalaryDetail>().eq(SalaryDetail::getBaseSalaryDetailId, salaryDetailVO.getId()))));
		return R.data(salaryDetailVO);
	}

	private void initCode(){
		rankMap = baseInfoService.getChildMap(ValueSetConstant.RANK);
		deptService.list().parallelStream().forEach(dept -> deptMap.put(dept.getId(), dept.getDeptName()));
	}

	@Override
	public void goBackToStash(String formId) {
		handleStatus(Long.valueOf(formId), UNREVIEWED);
	}


	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public R initAdd(BaseSalaryDetail baseSalaryDetail) {
		String fillingYear = baseSalaryDetail.getFillingYear();
		if (StringUtil.isBlank(fillingYear)){
			return R.fail("请选选择填报年度");
		}

		String fillingUnitId = TokenUtil.getTokenOrgId();
		BaseSalaryDetail old = getOne(new LambdaQueryWrapper<BaseSalaryDetail>()
				.eq(BaseSalaryDetail::getFillingUnitId, fillingUnitId)
				.eq(BaseSalaryDetail::getFillingYear, fillingYear));
		if (Optional.ofNullable(old).isPresent()){
			return R.fail("该年度已填报");
		}

		//保存主表
		BaseSalaryDetail initBase = new BaseSalaryDetail();
		initBase.setFillingYear(fillingYear);
		initBase.setFillingDate(DateUtil.now());
		initBase.setFillingUnitId(fillingUnitId);
		boolean result = saveOrUpdate(initBase);

		if (result){
			//子表数据保存
			String lastYear = String.valueOf(Integer.valueOf(fillingYear) - 1);
			//获取上月数据
			BaseSalaryDetail last = getOne(new LambdaQueryWrapper<BaseSalaryDetail>()
					.eq(BaseSalaryDetail::getFillingUnitId, fillingUnitId)
					.eq(BaseSalaryDetail::getFillingYear, lastYear));

			if (!Optional.ofNullable(last).isPresent()){
				return new R(CommonCode.SUCCESS);
			}
			List<SalaryDetailVO> salaryDetailVOS = salaryDetailWrapper.entityToVO(salaryDetailService.list(new LambdaQueryWrapper<SalaryDetail>()
					.eq(SalaryDetail::getBaseSalaryDetailId, last.getId())));
			if (CollectionUtil.isEmpty(salaryDetailVOS)){
				return  new R(CommonCode.SUCCESS);
			}

			for (SalaryDetailVO salaryDetailVO : salaryDetailVOS){
				SalaryDetail salaryDetail = new SalaryDetail();
				BeanUtils.copyProperties(salaryDetailVO, salaryDetail);
				salaryDetail.setId(null);
				salaryDetail.setBaseSalaryDetailId(initBase.getId());

				salaryDetail.setLastYearSalary(salaryDetail.getYearSalary());
				salaryDetail.setLastYearMiddleSalary(salaryDetail.getYearMiddleSalary());
				salaryDetail.setChangeCondition(null);
				salaryDetailService.saveOrUpdate(salaryDetail);
			}

		}
		return R.status(result);

	}

	@Override
	@Async("ttlExecutor")
	public Future<ImportResult> importExcel(String progressId, InputStream inputStream) {
		String progress = "progress";
		String key = progressId + "#half:hour";
		try {
			byte[] bytes = IOUtils.toByteArray(inputStream);
			inputStream = new ByteArrayInputStream(bytes);


			List<Object> baseList = new ArrayList<>();
			EasyExcel.read(inputStream).build()
					.read(EasyExcel.readSheet(0).headRowNumber(1).head(BaseSalaryDetailExcelBean.class)
							.registerReadListener(new PageReadListener<>(list -> baseList.addAll(list))).build());

			Map<String, Map<String, String>> mapRef= getRef();

			ImportResult baseResult = checkBaseData(mapRef, baseList);
			if (!baseResult.isSuccess()){
				CacheUtil.put(progress, progress, key, baseResult.getMsg());
				return new AsyncResult<>(baseResult);
			}

			inputStream.reset();
			List<Object> childList = new ArrayList<>();
			EasyExcel.read(inputStream).build()
					.read(EasyExcel.readSheet(1).headRowNumber(2).head(SalaryDetailExcelBean.class)
							.registerReadListener(new PageReadListener<>(list -> childList.addAll(list))).build());
			Map<String, StaffFiles> staffRef =  staffFilesService.list(new LambdaQueryWrapper<StaffFiles>()
					.eq(StaffFiles::getCreateCompanyId, TokenUtil.getTokenOrgId()).eq(StaffFiles::getIsOut, 1))
					.stream().collect(Collectors.toMap(staffFiles ->  EncryptUtil.decryptBase64(staffFiles.getStaffCode(), BASE64_KEY), staffFiles -> staffFiles));
			ImportExcelUtil.filterEmpty(childList);
			ImportResult childResult = checkChildData(mapRef, staffRef, childList, progressId);
			if (!childResult.isSuccess()){
				CacheUtil.put(progress, progress, key, childResult.getMsg());
				return new AsyncResult<>(childResult);
			}

			// 主表信息
			BaseSalaryDetail baseSalaryDetail = (BaseSalaryDetail) ImportExcelUtil.getEntityByExcelBean((BaseSalaryDetailExcelBean) baseList.get(0), new BaseSalaryDetail());
			BaseSalaryDetail old = getOldData(baseSalaryDetail);
			if (Optional.ofNullable(old).isPresent()){
				//如果有老数据 则删除子表旧数据
				baseSalaryDetail.setId(old.getId());
				salaryDetailService.deleteByBaseId(old.getId());
			}else {
				saveOrUpdate(baseSalaryDetail);
			}

			int count = 0;
			int size = childList.size();
			// 年度新增股权投资计划数据
			for (Object readExcel : childList) {
				SalaryDetail salaryDetail = (SalaryDetail) ImportExcelUtil.getEntityByExcelBean((SalaryDetailExcelBean)readExcel,new SalaryDetail());
				//入库
				try {
					salaryDetail.setBaseSalaryDetailId(baseSalaryDetail.getId());
					setChildStaffInfo(salaryDetail, staffRef, baseSalaryDetail.getFillingMonth());
					salaryDetailService.saveOrUpdate(salaryDetail);
					count++;
					int value = count * 100 / size;
					CacheUtil.put(progress, progress, key, value+100);
				} catch (Exception e) {
					log.error(ExceptionUtils.getFullStackTrace(e));
					log.error(salaryDetail + "导入失败");
					CacheUtil.put(progress, progress, key,salaryDetail + "导入失败");
					return new AsyncResult<>(new ImportResult(false,salaryDetail + "导入失败"));
				}
			}

		} catch (Exception e) {
			log.error(ExceptionUtils.getFullStackTrace(e));
			log.error("解析失败");
			CacheUtil.put(progress, progress, key,"解析失败");
			return new AsyncResult<>(new ImportResult(false,"解析失败"));
		}

		CacheUtil.put(progress, progress, key,"导入成功");
		return new AsyncResult<>(new ImportResult(true,"导入成功"));
	}

	@Override
	public void exportTemplateExcel(HttpServletResponse response, OutputStream os) {
		try {
			String fname = "市属企业工资总额本部职工明细导入模板";
			os = response.getOutputStream();//取得输出流
			response.reset();//清空输出流
			//下面是对中文文件名的处理
			response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式
			InputStream inputStream = this.getClass().getResourceAsStream("/exceldemo/salaryDetailImport.xlsx");
			fname = java.net.URLEncoder.encode(fname, "UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(fname.getBytes("UTF-8"), "UTF-8") + ".xlsx");

			response.setContentType("application/msexcel");//定义输出类型
			int len;
			byte[] b = new byte[2048];
			while ((len = inputStream.read(b)) != -1) {
				os.write(b, 0, len);
			}
			response.setHeader("Content-Length", String.valueOf(inputStream.available()));

			inputStream.close();
			os.close();
		}catch (Exception e){
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
	}

	/**
	 * 设置员工档案相关信息
	 * @param salaryDetail
	 * @param staffFilesMap
	 */
	private void setChildStaffInfo(SalaryDetail salaryDetail, Map<String, StaffFiles> staffFilesMap, String fillingMonth){
		StaffFiles staffFiles = staffFilesMap.get(salaryDetail.getStaffFilesCode());
//		salaryDetail.setIsChange(staffFilesService.getIsChange(staffFiles.getId(), fillingMonth));
		salaryDetail.setDepartmentNameId(Long.valueOf(staffFiles.getDepartmentNameId()));
		salaryDetail.setStaffFilesId(staffFiles.getId());
		salaryDetail.setStaffName(staffFiles.getStaffName());
		salaryDetail.setJobNameId(staffFiles.getJobNameId());
		salaryDetail.setRankId(staffFiles.getRankId());
		salaryDetail.setIsLeader(1);
		salaryDetail.setIsMiddle(1);
		if ("027001".equals(staffFiles.getManagementCategoryId())){
			salaryDetail.setIsLeader(2);
			salaryDetail.setDepartmentNameId(null);
		}
		if ("027002".equals(staffFiles.getManagementCategoryId())){
			salaryDetail.setIsMiddle(2);
		}

	}

	private BaseSalaryDetail getOldData(BaseSalaryDetail baseSalaryDetail){
		LambdaQueryWrapper<BaseSalaryDetail> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(BaseSalaryDetail::getFillingUnitId, baseSalaryDetail.getFillingUnitId());
		queryWrapper.eq(BaseSalaryDetail::getFillingYear, baseSalaryDetail.getFillingYear());
		return getOne(queryWrapper);
	}

	private Map<String,Map<String,String>> getRef() {
		Map<String, Map<String, String>> mapRefs = new HashMap<>(16);
		Map<String,String> unitRef = new HashMap<>(512);
		try{
			List<PageData> allOrgs =  orgzationDao.list(null);
			if (CollectionUtil.isNotEmpty(allOrgs)){
				for (PageData pageData : allOrgs){
					unitRef.put((String)pageData.get("name"), (String)pageData.get("id"));
				}

			}
		}catch (Exception e){
			log.error(ExceptionUtils.getFullStackTrace(e));
		}
		mapRefs.put("unitRef",unitRef);


		return mapRefs;
	}


	private ImportResult checkBaseData(Map<String,Map<String,String>> mapRef, List<Object> readExcels) {
		ImportResult importResult = new ImportResult(true,"");

		StringBuilder msg = new StringBuilder();

		if (CollectionUtil.isNotEmpty(readExcels)){
			int index = 2;
			BaseSalaryDetailExcelBean excelBean = (BaseSalaryDetailExcelBean) readExcels.get(0);

			//判空
			msg.append(ImportExcelUtil.checkEmpty("2", "填报单位",
					excelBean.getFillingUnitId(), index).getMsg());
			msg.append(ImportExcelUtil.checkEmpty("2", "填报年度",
					excelBean.getFillingYear(), index).getMsg());
			msg.append(ImportExcelUtil.checkEmpty("2", "填报期间",
					excelBean.getFillingDate(), index).getMsg());
			//判断类型
			msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_INTEGER, "2", "填报年度",
					excelBean.getFillingYear(), index).getMsg());
			msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_DATE, "2", "填报期间",
					excelBean.getFillingDate(), index).getMsg());
			//判断完类型若有错直接返回
			if (msg.toString().length() > 0) {
				return new ImportResult(false, msg.toString());
			}

			//对象和字典是否存在校验
			//单位名称
			excelBean.setFillingUnitId(StringUtil.cleanChars(excelBean.getFillingUnitId()));
			if(mapRef.get("unitRef").containsKey(excelBean.getFillingUnitId())){
				String companyName = excelBean.getFillingUnitId();
				excelBean.setFillingUnitId(mapRef.get("unitRef").get(excelBean.getFillingUnitId()));
				if(!TokenUtil.getTokenOrgId().equals(excelBean.getFillingUnitId())){
					msg.append("sheet2第" + index + "行(填报单位=" + companyName + ")不是当前登录单位\n");
				}
			}else if(!StringUtil.isEmpty(excelBean.getFillingUnitId())){
				msg.append("sheet2第" + index + "行(填报单位=" + excelBean.getFillingUnitId() + ")在系统中不存在\n");
			}

			QueryWrapper<BaseSalaryDetail> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("filling_unit_id", excelBean.getFillingUnitId());
			queryWrapper.eq("filling_year", excelBean.getFillingYear());
			queryWrapper.ne("status", FormStatusConstant.UNREVIEWED);
			if (Optional.ofNullable(getOne(queryWrapper)).isPresent()){
				msg.append("sheet1该年度数据 已上报\n");
			}

		}else {
			msg.append("sheet1填报单位未填写\n");
		}

		//统一放置报错
		if (msg.toString().length()>0) {
			importResult = new ImportResult(false, msg.toString());
		}
		return importResult;

	}

	private ImportResult checkChildData(Map<String,Map<String,String>> mapRef, Map<String, StaffFiles> staffFilesMap, List<Object> readExcels, String progressId) {

		ImportResult importResult = new ImportResult(true,"");

		StringBuilder msg = new StringBuilder();
		for (Object readExcel : readExcels) {
			SalaryDetailExcelBean excelBean = (SalaryDetailExcelBean)readExcel;
			int index = readExcels.indexOf(readExcel) + 1;

			//判空
			msg.append(ImportExcelUtil.checkEmpty("2", "证件号",
					excelBean.getStaffFilesCode(), index).getMsg());
			msg.append(ImportExcelUtil.checkEmpty("2", "上年薪酬实发数(万元) 总额(万元)",
					excelBean.getLastYearSalary(), index).getMsg());
			msg.append(ImportExcelUtil.checkEmpty("2", "上年薪酬实发数(万元) 其中:中层(万元)",
					excelBean.getLastYearMiddleSalary(), index).getMsg());
			msg.append(ImportExcelUtil.checkEmpty("2", "本年发放数(万元) 总额(万元)",
					excelBean.getYearSalary(), index).getMsg());
			msg.append(ImportExcelUtil.checkEmpty("2", "本年发放数(万元) 其中:中层(万元)",
					excelBean.getYearMiddleSalary(), index).getMsg());
			msg.append(ImportExcelUtil.checkEmpty("2", "平均 总额(万元)",
					excelBean.getAverageNumber(), index).getMsg());
			msg.append(ImportExcelUtil.checkEmpty("2", "平均 其中:中层(万元)",
					excelBean.getMiddleAverageNumber(), index).getMsg());


			//判断类型
			msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "上年薪酬实发数(万元) 总额(万元)",
					excelBean.getLastYearSalary(), index).getMsg());
			msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "上年薪酬实发数(万元) 其中:中层(万元)",
					excelBean.getLastYearMiddleSalary(), index).getMsg());
			msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "本年发放数(万元) 总额(万元)",
					excelBean.getYearSalary(), index).getMsg());
			msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "本年发放数(万元) 其中:中层(万元)",
					excelBean.getYearMiddleSalary(), index).getMsg());
			msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "平均 总额(万元)",
					excelBean.getAverageNumber(), index).getMsg());
			msg.append(ImportExcelUtil.checkType(ImportExcelUtil.TYPE_BIGDECIMAL, "2", "平均 其中:中层(万元)",
					excelBean.getMiddleAverageNumber(), index).getMsg());
		}
		//判断完类型若有错直接返回
		if (msg.toString().length() > 0) {
			return new ImportResult(false, msg.toString());
		}

		//对象和字典是否存在校验
		int size=readExcels.size();
		int count=0;
		for (Object readExcel : readExcels) {
			SalaryDetailExcelBean excelBean = (SalaryDetailExcelBean) readExcel;
			int index = readExcels.indexOf(readExcel) + 3;
			//身份证
			if(!staffFilesMap.containsKey(excelBean.getStaffFilesCode())){
				msg.append("sheet3第" + index + "行(证件号 =" + excelBean.getStaffFilesCode() + ")在该单位下不存在不存在\n");
			}
			excelBean.setDepartmentNameId(null);

			count++;
			int value = count * 100 / size;
			CacheUtil.put("progress","progress",progressId, value);
		}

		//统一放置报错
		if (msg.toString().length()>0) {
			importResult = new ImportResult(false, msg.toString());
		}
		return importResult;
	}

}
